package com.dormitory.management.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dormitory.management.system.entity.Health;
import com.dormitory.management.system.enums.UserEnum;
import com.dormitory.management.system.req.HealthPageReq;
import com.dormitory.management.system.req.HealthSaveReq;
import com.dormitory.management.system.req.HealthUpdateReq;
import com.dormitory.management.system.resp.HealthPageResp;
import com.dormitory.management.system.entity.Housemaster;
import com.dormitory.management.system.mapper.BuildingMapper;
import com.dormitory.management.system.mapper.HealthMapper;
import com.dormitory.management.system.mapper.HousemasterMapper;
import com.dormitory.management.system.mapper.StudentMapper;
import com.dormitory.management.system.service.HealthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dormitory.management.system.service.UserService;
import com.dormitory.managemnet.util.utils.BeanUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

/**
 * <p>
 * 防疫健康表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-12-17
 */
@Service
public class HealthServiceImpl extends ServiceImpl<HealthMapper, Health> implements HealthService {
    @Autowired
    UserService userService;
    @Autowired
    HousemasterMapper housemasterMapper;
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    BuildingMapper buildingMapper;

    @Override
    public IPage<HealthPageResp> getPage(HealthPageReq req) {
        Page<HealthPageResp> page = new Page<>(req.getPageCurrent(), req.getPageSize());
        QueryWrapper<HealthPageResp> query = new QueryWrapper<>();
        if (userService.getRoleKey(req.getUsername()).equals(UserEnum.USER_HOUSEMASTER.getRoleKey())) {
            Housemaster housemaster = housemasterMapper.selectOne(new QueryWrapper<Housemaster>().lambda().eq(Housemaster::getIdentityCard, req.getUsername()));
            query.eq(housemaster.getBuildingId() != null, "housemaster.building_id", housemaster.getBuildingId())
                    .eq(housemaster.getIdentityCard() != null, "housemaster.identity_card", req.getUsername())
                    .like(req.getStuId() != null, "student.stu_id", req.getStuId())
                    .like(req.getRoom() != null, "room.room", req.getRoom())
                    .eq(req.getIsHealthStatus()!=null,"health.is_health_status",req.getIsHealthStatus())
                    .eq(req.getIsHighRiskAreas()!=null,"health.is_high_risk_areas",req.getIsHighRiskAreas())
                    .eq(req.getIsPassHighRiskAreas()!=null,"health.is_pass_high_risk_areas",req.getIsHighRiskAreas())
                    .eq(req.getIsInSchool()!=null,"health.is_in_school",req.getIsInSchool())
                    .eq("housemaster.status_id",0)
                    .eq("student.status_id",0)
                    .eq("health.status_id",0)
                    .apply(req.getGmtModifiedEarliest()!=null,"TO_DAYS(health.gmt_modified) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtModifiedEarliest(), "yyyy-MM-dd HH:mm:ss")+"')")
                    .apply(req.getGmtModifiedLatest()!=null,"TO_DAYS(health.gmt_modified) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtModifiedLatest(), "yyyy-MM-dd HH:mm:ss")+"')");
//                    .between(req.getGmtModifiedEarliest() != null&&req.getGmtModifiedLatest() != null,"health.gmt_modified",req.getGmtModifiedEarliest(),req.getGmtModifiedLatest());
            return this.baseMapper.getHealthPageHousemaster(page, query);
        } else if (userService.getRoleKey(req.getUsername()).equals(UserEnum.USER_STUDENT.getRoleKey())) {
            query.eq(req.getUsername() != null, "student.stu_id", req.getUsername())
                    .eq("student.status_id",0)
                    .eq("health.status_id",0)
                    .eq(req.getIsHealthStatus()!=null,"health.is_health_status",req.getIsHealthStatus())
                    .eq(req.getIsHighRiskAreas()!=null,"health.is_high_risk_areas",req.getIsHighRiskAreas())
                    .eq(req.getIsPassHighRiskAreas()!=null,"health.is_pass_high_risk_areas",req.getIsHighRiskAreas())
                    .eq(req.getIsInSchool()!=null,"health.is_in_school",req.getIsInSchool())
                    .apply(req.getGmtModifiedEarliest()!=null,"TO_DAYS(health.gmt_modified) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtModifiedEarliest(), "yyyy-MM-dd HH:mm:ss")+"')")
                    .apply(req.getGmtModifiedLatest()!=null,"TO_DAYS(health.gmt_modified) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtModifiedLatest(), "yyyy-MM-dd HH:mm:ss")+"')");
//                    .between(req.getGmtModifiedEarliest() != null&&req.getGmtModifiedLatest() != null,"health.gmt_modified",req.getGmtModifiedEarliest(),req.getGmtModifiedLatest());
            return this.baseMapper.getHealthPageStudent(page, query);
        }else if(userService.getRoleKey(req.getUsername()).equals(UserEnum.USER_ADMIN.getRoleKey())) {
            query.eq("health.status_id",0)
                    .like(req.getStuId() != null, "student.stu_id", req.getStuId())
                    .like(req.getRoom() != null, "room.room", req.getRoom())
                    .eq(req.getIsHealthStatus()!=null,"health.is_health_status",req.getIsHealthStatus())
                    .eq(req.getIsHighRiskAreas()!=null,"health.is_high_risk_areas",req.getIsHighRiskAreas())
                    .eq(req.getIsPassHighRiskAreas()!=null,"health.is_pass_high_risk_areas",req.getIsHighRiskAreas())
                    .eq(req.getIsInSchool()!=null,"health.is_in_school",req.getIsInSchool())
                    .apply(req.getGmtModifiedEarliest()!=null,"TO_DAYS(health.gmt_modified) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtModifiedEarliest(), "yyyy-MM-dd HH:mm:ss")+"')")
                    .apply(req.getGmtModifiedLatest()!=null,"TO_DAYS(health.gmt_modified) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtModifiedLatest(), "yyyy-MM-dd HH:mm:ss")+"')");
//                    .between(req.getGmtModifiedEarliest() != null&&req.getGmtModifiedLatest() != null,"health.gmt_modified",req.getGmtModifiedEarliest(),req.getGmtModifiedLatest());
            return this.baseMapper.getHealthPageUser(page,query);
        }
        return null;
    }

    @Override
    public boolean save(HealthSaveReq req){
        return this.baseMapper.insert(BeanUtil.copyProperties(req,Health.class))>0;
    }

    @Override
    public boolean delete(Long id){
        return this.baseMapper.deleteById(id)>0;
    }

    @Override
    public boolean update(HealthUpdateReq req) {
        return this.baseMapper.updateById(BeanUtil.copyProperties(req,Health.class))>0;
    }

    //今日管理楼栋内 已填报学生数
    @Override
    public int countTodayDeclared(String username) {
        QueryWrapper<Integer> query = new QueryWrapper<>();
        query.eq("housemaster.identity_card",username)
                .eq("housemaster.status_id",0)
                .eq("student.status_id",0)
                .eq("health.status_id",0)
                .between("health.gmt_create", LocalDate.now(),LocalDate.now().plusDays(1));
        return this.baseMapper.countTodayDeclared(query);
    }

    //昨天有多少人是异常
    @Override
    public int countYesterdayException(String username) {
        QueryWrapper<Integer> query = new QueryWrapper<>();
        query.eq("student.status_id",0)
                .eq("housemaster.identity_card",username)
                .eq("housemaster.status_id",0)
                .eq("health.status_id",0)
                .eq("health.is_health_status",1)
                .between("health.gmt_create", LocalDate.now().minusDays(1),LocalDate.now());
        return this.baseMapper.countYesterdayException(query);
    }

    //今天有多少人是异常
    @Override
    public  int countTodayException(String username) {
        QueryWrapper<Integer> query = new QueryWrapper<>();
        query.eq("student.status_id",0)
                .eq("housemaster.identity_card",username)
                .eq("housemaster.status_id",0)
                .eq("health.status_id",0)
                .eq("health.is_health_status",1)
                .ge("health.gmt_create",LocalDate.now());
        return this.baseMapper.countTodayException(query);
    }

    @Override
    public Health select(String username) {
        QueryWrapper<Health> query = new QueryWrapper<>();
        query.eq("health.status_id",0)
                .between("health.gmt_create", LocalDate.now(),LocalDate.now().plusDays(1))
                .eq("health.stu_id",username);
        return this.baseMapper.selectOne(query);
    }

}
